package com.example.aicompositiongrader;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.room.Room;

import com.example.aicompositiongrader.database.AppDatabase;
import com.example.aicompositiongrader.database.HistoryRecord;
import com.example.aicompositiongrader.model.CompositionResponse;
import com.example.aicompositiongrader.model.DeepSeekRequest;
import com.example.aicompositiongrader.network.ApiService;
import com.example.aicompositiongrader.network.RetrofitClient;
import com.example.aicompositiongrader.utils.ImagePickerUtils;
import com.example.aicompositiongrader.utils.OcrManager;
import com.google.gson.Gson;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {

    private EditText editTextComposition;
    private Button buttonAnalyze;
    private Button buttonUploadImage;
    private ProgressBar progressBar;

    private CompositeDisposable compositeDisposable = new CompositeDisposable();
    private ApiService apiService;
    private OcrManager ocrManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        initViews();
        // 清除输入框内容
        editTextComposition.setText("");
        apiService = RetrofitClient.getApiService();
        initOcrManager();
    }

    private void initViews() {
        editTextComposition = findViewById(R.id.editTextComposition);
        buttonAnalyze = findViewById(R.id.buttonAnalyze);
        buttonUploadImage = findViewById(R.id.buttonUploadImage);
        progressBar = findViewById(R.id.progressBar);

        buttonAnalyze.setOnClickListener(v -> analyzeComposition());
        buttonUploadImage.setOnClickListener(v -> handleImageUpload());
    }

    private void initOcrManager() {
        ocrManager = new OcrManager(this);
        ocrManager.setListener(new OcrManager.OcrResultListener() {
            @Override
            public void onSuccess(String text) {
                // 将识别到的文字填充到输入框
                editTextComposition.setText(text);
                Toast.makeText(MainActivity.this, "文字识别成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(String error) {
                Toast.makeText(MainActivity.this, "识别失败: " + error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void handleImageUpload() {
        if (ImagePickerUtils.checkPermissions(this)) {
            showImagePickerDialog();
        } else {
            ImagePickerUtils.requestPermissions(this);
        }
    }

    private void showImagePickerDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择图片来源");
        builder.setItems(new String[]{"相机拍摄", "从相册选择"}, (dialog, which) -> {
            if (which == 0) {
                ImagePickerUtils.openCamera(MainActivity.this);
            } else {
                ImagePickerUtils.openGallery(MainActivity.this);
            }
        });
        builder.show();
    }

    private void analyzeComposition() {
        String text = editTextComposition.getText().toString().trim();
        if (text.isEmpty()) {
            Toast.makeText(this, "请输入作文内容", Toast.LENGTH_SHORT).show();
            return;
        }

        showLoading(true);

        // 使用DeepSeek请求模型
        DeepSeekRequest request = new DeepSeekRequest(text);
        compositeDisposable.add(
                apiService.analyzeComposition(request)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(
                                deepSeekResponse -> {
                                    showLoading(false);
                                    // 将DeepSeek响应转换为应用内部格式
                                    CompositionResponse response = deepSeekResponse.toCompositionResponse();
                                    handleAnalysisResult(response, text);
                                },
                                throwable -> {
                                    showLoading(false);
                                    Toast.makeText(MainActivity.this, "分析失败: " + throwable.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                        )
        );
    }

    private void handleAnalysisResult(CompositionResponse response, String originalText) {
        // 保存到数据库
        saveToDatabase(originalText, response);

        // 跳转到结果页面
        Intent intent = new Intent(this, ResultActivity.class);
        Gson gson = new Gson();
        intent.putExtra("response", gson.toJson(response));
        startActivity(intent);
    }

    private void saveToDatabase(String originalText, CompositionResponse response) {
        new Thread(() -> {
            try {
                Gson gson = new Gson();
                String feedbackJson = gson.toJson(response);
                long timestamp = System.currentTimeMillis();

                HistoryRecord record = new HistoryRecord(originalText, feedbackJson, timestamp);
                AppDatabase db = Room.databaseBuilder(getApplicationContext(),
                        AppDatabase.class, "composition-database").build();
                db.historyDao().insert(record);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void showLoading(boolean isLoading) {
        progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        buttonAnalyze.setEnabled(!isLoading);
        buttonUploadImage.setEnabled(!isLoading);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == ImagePickerUtils.PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                showImagePickerDialog();
            } else {
                Toast.makeText(this, "需要相机和存储权限才能上传图片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == ImagePickerUtils.REQUEST_CAMERA) {
                // 处理相机拍摄的图片
                String imagePath = ImagePickerUtils.getCurrentPhotoPath();
                if (imagePath != null) {
                    ocrManager.recognizeTextFromPath(imagePath);
                }
            } else if (requestCode == ImagePickerUtils.REQUEST_GALLERY) {
                // 处理相册选择的图片
                Uri selectedImage = data.getData();
                if (selectedImage != null) {
                    ocrManager.recognizeTextFromUri(this, selectedImage);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        compositeDisposable.dispose();
        if (ocrManager != null) {
            ocrManager.close();
        }
    }
}
